/*
 * Copyright (C) 2016 Lokiy(liulongke@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  　　　　http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package com.lokiy.databinding.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.lokiy.core.adapter.BasicAdapter
import com.lokiy.databinding.BR

/**
 * BasicDatabindAdapter
 * lokiy
 * 2021-02-01
 */
open class BasicDataBindingAdapter<T>(private val emptyData: EmptyData?, onLoadMoreListener: (BasicAdapter<T>.() -> Unit)?) : BasicAdapter<T>(20, onLoadMoreListener) {

    constructor(onLoadMoreListener: (BasicAdapter<T>.() -> Unit)?) : this(null,  onLoadMoreListener)

    override fun getItemViewType1(position: Int): Int = getItem(position)?.let {
        if (it is IItemType) {
            it.itemViewType
        } else {
            0
        }
    } ?: 0

    override fun onCreateViewHolder1(parent: ViewGroup, viewType: Int): Holder<T?> {
        val binding = DataBindingUtil.inflate<ViewDataBinding>(LayoutInflater.from(parent.context), viewType, parent, false)
        return BindingHolder(binding)
    }

    public class BindingHolder<T> constructor(private var binding: ViewDataBinding) : Holder<T>(binding.root) {

        override fun bindData(data: T?) {
            binding.setVariable(BR.item, data)
            binding.setVariable(BR.position, adapterPosition)
            binding.executePendingBindings()
        }

        @Suppress("UNCHECKED_CAST")
        fun <T : ViewDataBinding> getBinding(): T = binding as T
    }

    override fun getEmptyImage(): Int = emptyData?.imageRes ?: super.getEmptyImage()

    override fun getEmptyText(): String = emptyData?.emptyText ?: super.getEmptyText()

    interface IItemType {
        /**
         * itemViewType
         */
        val itemViewType: Int
    }

    class EmptyData(val imageRes: Int, val emptyText: String)

}